<template>
  <div class="add-invite-qrcode">
    <div class="invite-list">
      <cell-group>
        <field
          v-model="grade.level_name"
          clearable
          label="代理级别："
          right-icon="arrow-down"
          readonly
          placeholder="请选择代理级别"
          @click="showPopup = true, popupType = 'agent'"
        />

        <field
          v-model="showTime"
          label="有效期限："
          placeholder="请选择有效期限"
          right-icon="arrow-down"
          readonly
          @click="showPopup = true, popupType = 'time'"
        />

        <field v-model="count" label="可用次数：" type="number" placeholder="请输入可用次数" />
      </cell-group>
    </div>

    <div class="submit">
      <van-button
        type="info"
        size="large"
        @click="insertInviteQRCode"
        :disabled="isSubmitting"
      >{{isSubmitting ? '正在提交' : '确认'}}</van-button>
    </div>

    <popup :show="showPopup" @onCancel="onCancel">
      <div v-if="popupType == 'agent'">
        <picker
          @cancel="onCancel"
          value-key="level_name"
          show-toolbar
          :columns="agencyLevelList"
          @confirm="onConfirm"
        />
      </div>

      <div v-if="popupType == 'time'">
        <!-- <datetime-picker
          show-toolbar
          v-model="currentDate"
          type="date"
          :min-date="minDate"
          :formatter="formatter"
          @cancel="onCancel"
          @confirm="onConfirm"
        />-->
        <picker
          @cancel="onCancel"
          value-key="name"
          show-toolbar
          :columns="timeList"
          @confirm="onConfirm"
        />
      </div>
    </popup>
  </div>
</template>

<script>
import {
  Icon,
  Picker,
  Button,
  Field,
  Cell,
  CellGroup,
  DatetimePicker,
  Toast
} from "vant";
import popup from "../components/popup.vue";
// import fieldItem from "../components/field_item.vue";
import http from "../service/myHttp.js";
import urls from "../service/url.js";
import { mapState } from "vuex";
let moment = require("moment");

export default {
  components: {
    Icon,
    Picker,
    popup,
    vanButton: Button,
    Field,
    Cell,
    CellGroup,
    DatetimePicker,
    Toast
  },
  data() {
    return {
      grade: "",
      startTime: "",
      endTime: "",
      showTime: "",
      count: "",
      popupType: "agent",
      currentDate: new Date(),
      minDate: new Date(),
      showPopup: false,
      columns: [
        {
          value: "方式一",
          defaultIndex: 1
        },
        {
          value: "方式二",
          defaultIndex: 2
        }
      ],
      agencyLevelList: [
        // {
        //   id: 0,
        //   level_name: "全部"
        // }
      ],
      timeList: [
        {
          id: 1,
          name: "1 小时",
          operation: [1, "h"]
        },
        {
          id: 2,
          name: "8 小时",
          operation: [8, "h"]
        },
        {
          id: 3,
          name: "1 天",
          operation: [1, "d"]
        },
        {
          id: 4,
          name: "7 天",
          operation: [7, "d"]
        },
        {
          id: 5,
          name: "15 天",
          operation: [15, "d"]
        },
        {
          id: 6,
          name: "30 天",
          operation: [30, "d"]
        },
        {
          id: 7,
          name: "60 天",
          operation: [60, "d"]
        },
        {
          id: 8,
          name: "90 天",
          operation: [90, "d"]
        },
        {
          id: 9,
          name: "180 天",
          operation: [180, "d"]
        },
        {
          id: 10,
          name: "365 天",
          operation: [365, "d"]
        }
      ],
      isSubmitting: false
    };
  },
  computed: {
    ...mapState({
      userinfo: state => state.login_module.userinfo,
      countAlias: "userinfo"
    })
  },
  mounted() {
    this.getAgencyLevel();
  },
  methods: {
    // 创建二维码
    insertInviteQRCode() {
      var patten = /^[1-9]+$/;

      if (!this.grade) {
        Toast("请选择代理级别");
        return false;
      } else if (!this.endTime) {
        Toast("请选择有效期限");
        return false;
      } else if (!patten.test(Number(this.count))) {
        console.log("可用次数：", Number(this.count));
        Toast("请填写可用次数");
        return false;
      }

      // console.log(this.time)
      this.isSubmitting = true;
      http
        .post(urls.CJEWM, {
          createBy: this.userinfo.id,
          levelId: this.grade.id,
          endTime: this.endTime,
          startTime: this.startTime,
          usableNumber: this.count
        })
        .then(res => {
          console.log(res);
          this.isSubmitting = false;

          if (res.data.code == 200) {
            Toast.success("新增二维码成功");

            this.$router.replace({
              path: "/my_invite"
            });
          }
        });
    },

    // 获取代理等级列表
    getAgencyLevel() {
      return http
        .post(urls.JZDLXLK, {
          id: this.userinfo.id,
          tokenid: this.userinfo.id
        })
        .then(res => {
          if (res.data.code == 200) {
            this.agencyLevelList.push(...res.data.data);
            // this.agencyLevelList.push({ id: 0, level_name: "全部" });
          }
        });
    },

    // 时间格式
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      }
      return value;
    },

    onCancel() {
      this.showPopup = false;
    },

    // popup确定时，根据popupType做不同处理
    onConfirm(value) {
      if (this.popupType == "agent") {
        this.grade = value;
      } else if (this.popupType == "time") {
        let date = new Date();
        this.startTime = moment(date).format("YYYY-MM-DD HH:mm:ss");
        this.endTime = moment(date)
          .add(value.operation[0], value.operation[1])
          .format("YYYY-MM-DD HH:mm:ss");
        this.showTime = value.name;
      }
      // this.value = value;
      this.showPopup = false;
      console.log(this.value);
    }
  }
};
</script>

<style scoped>
.invite-list {
  background-color: #fff;
}

.submit {
  margin-top: 20px;
}
</style>